import React, {Component} from 'react';

import './index.css'
// 引入 store 用于获取redux中保存的状态
import store from "../../redux/store";

export default class Count extends Component {

    // componentDidMount() {
    //     // 检测redux中状态的变化，如果有变化就调 render
    //     store.subscribe(() => {
    //         this.setState({});
    //     })
    // }

    increment = () => {
        const {value} = this.selectValue;
        // 通知redux操作
        store.dispatch({
            type: 'increment',
            data: value*1
        })
    }

    decrement = () => {
        const {value} = this.selectValue;
        store.dispatch({
            type: 'decrement',
            data: value*1
        })
    }

    incrementIfOdd = () => {
        const {value} = this.selectValue;
        const count = store.getState();
        if (count % 2 !== 0) {
            store.dispatch({
                type: 'increment',
                data: value*1
            })
        }

    }

    incrementAsync = () => {
        const {value} = this.selectValue;
        setTimeout(() => {
            store.dispatch({
                type: 'increment',
                data: value*1
            })
        },  1000)
    }

    render() {
        return (
            <div>
                <h1>当前和为：{store.getState()}</h1>
                <select className="sel" ref={c => this.selectValue = c}>
                    <option value="1">1</option>
                    <option value="2">2</option>
                    <option value="3">3</option>
                    <option value="4">4</option>
                </select>

                <div className="btns">
                    <button onClick={this.increment}>+</button>
                    <button onClick={this.decrement}>-</button>
                    <button onClick={this.incrementIfOdd}>当前为奇数时加</button>
                    <button onClick={this.incrementAsync}>异步+</button>
                </div>
            </div>
        );
    }
}